// components/bdEditer/bdEditer.js
Component({
  externalClasses: ['editer-class'],
  properties:{nodes:{type:String,value:"",observer:"_propertyChange",},editerControl:Boolean,},
  data: {},
  methods: {
    _propertyChange:function(newVal,oldVal){if(newVal.constructor === String){let answer,text,node,els = [];text = this._getElementText(newVal); node = this._getElementNode(newVal); for(;node.length!== 0;){if(text.length === node.length) els.push(node.shift());else els.push(text.shift())}answer = this._recombine(els).children;this.setData({content:answer})}},
    _recombine: function(orgin, answer = {}) {
      let fun = (orgin, answer = {}) => {
        answer.children = [];
        for (let ind = 0; orgin.length != 0;) {
          let cur = orgin.shift();
          if (cur.type == 'text' && !cur.text) continue;
          if (cur.sign == 'start') {
            fun(orgin, cur)
          } else if (cur.sign == 'end') {
            delete cur.sign
            break;
          }
          delete cur.sign
          answer.children.push(cur)
        }
        return answer;
      }
      return fun(orgin, answer)
    },
    _getElementText: function(str) {
      return str.match(/(^|>).*?(<|$)/gi).map((cur, index, arr) => {
        let node = {};
        node.text = cur.substring(index === 0 ? 0 : 1, index === arr.length - 1 ? cur.length : cur.length - 1);
        node.type = 'text'
        return node;
      });
    },
    _getElementNode: function(str) {
      return str.match(/<.*?>/gi).map(cur => {
        let slashPost, node = {};
        node.type = 'node';
        cur = cur.substring(1, cur.length - 1);
        slashPost = cur.lastIndexOf('/');
        if(slashPost == 0){node.sign = 'end'}else{node.name = cur.match(/[\w-]+/i)[0]; node.attrs = this._strToObj(cur); this._setWidth(node); if(slashPost == cur.length - 1) node.sign = 'single'; else node.sign = 'start'}
        return node;
      })
    },
    _setWidth:function(node){node.attrs.style = `max-width:100%;${node.attrs.style ? node.attrs.style:''}`; if(node.name == 'img'){node.attrs.width = '100%'; node.attrs.height = 'auto'}},
    _strToObj: function(str) {
      let attrs = str.match(/[\S]*?=".*?"/gi),
        answer = {};
        if(attrs){for(let str of attrs){let fe = str.indexOf('=');answer[str.substring(0,fe)] = str.substring(fe+2,str.length - 1)}}
      return answer
    },
  }
})